package github.data_structure.string;

/**
 * @Author: DRevelation
 * @Date: 2020/12/24 19:32
 */
public class Int {
    public static void main(String[] args) {
        int n = 254;
        System.out.println(toBinaryString(n));
        System.out.println("====================");
        System.out.println(toHexString(n));
        System.out.println("====================");
        System.out.println(toString(n, 8));
    }

    /**
     * 转换成二进制
     *
     * @param n
     * @return
     */
    private static String toBinaryString(int n) {
        StringBuilder str = new StringBuilder();
        // 一个int占32位，右移一位，高位以0填充
        // 0x80000000 = 10000000000000000000000000000000 (32个0,循环32次)
        // 0x80000000 = Integer.MIN_VALUE
        for (int i = Integer.MIN_VALUE; i != 0; i >>>= 1) {
            System.out.println("i = " + Integer.toBinaryString(i));
            str.append((n & i) == 0 ? '0' : '1');
        }
        return str.toString();
    }

    /**
     * 转换为十六进制
     *
     * @param n
     * @return
     */
    private static String toHexString(int n) {
        StringBuilder str = new StringBuilder();
        while (n > 0) {
            // 除16取余法，余数存入str字符串
            int k = n % 16;
            // 将0-9，10-15转换成'0'-'9','A'-'F'
            str.insert(0, (char) (k <= 9 ? k + '0' : k + 'A' - 10));
            System.out.println("str = " + str);
            n /= 16;
        }
        return str.toString();
    }

    /**
     * 转换成任意进制
     *
     * @param n
     * @param radix
     * @return
     */
    private static String toString(int n, int radix) {
        StringBuilder str = new StringBuilder();
        while (n > 0) {
            int k = n % radix;
            str.insert(0, (char) (k <= 9 ? k + '0' : k - 10 + 'A'));
            n /= radix;
        }
        return str.toString();
    }
}
